/*================================================
 * 
 * Createtime : 2016/04/12
 * Author : luo yanming
 * Name : m.iknow.tm
 * 
 ================================================*/
define(function(require, exports, module) {
	var $ = require('jquery'),
		touch = require('touch'),
		swiper = require('swiper'),
		iknow = require('iknow');

    var index = {
        init: function(){
        	index.bind();
        },
        bind: function(){
        	index.cardSetTop();
        	index.indexHotareaMore();
        	index.getCard();
        	index.wechatShare();
        	
        	//search
        	var searchButton = $('.index .index-search .box');
        	touch.on(searchButton, 'tap', function(ev){
				location.href = '/search.html';
			});
        	
		    //add card
		    var btn_card_add = $('.index-card-add');
		    touch.on(btn_card_add, 'tap', function(ev){
		    	if(!iknow.isLocalStorageSupported()){
		    		iknow.alert('卡片功能暂不支持“无痕浏览”模式！请先关闭浏览器的“无痕浏览”！');
		    		return false;
		    	}
		    	location.href = '/card/cardlist.html';
		    });
        },
        indexHotareaMore: function(){
        	var $box = $('.index-hotarea .list ul'),
        		$arrow = $('.index-hotarea .arrow'),
        		$aimg = $arrow.find('img'),
        		$atxt = $arrow.find('h2');
        	
        	$.ajax({
                url:"/card/categories.html",
                dataType:"json",
                type:"post",
                data: {
                    
                },
                success:function(result) {
//                  	console.log(result);
        			var str = '';
                  	for(var i = 0; i < result.length; i++){
		        		str += '<li>';
						str += '<a href="/expert/slist.html?cateid='+ result[i].id +'">';
						str += '<img src="'+ cdnStaticDomain + result[i].roundCover +'">';
						str += '<h2 class="fs-26 t-c">'+ result[i].name +'</h2>';
						str += '</a>';
						str += '</li>';
                  	}
                  	$box.html(str);
                },
                error: function() {
                    iknow.alert("网络连接出错，请重试！");
                }
            });
        	
        	touch.on($arrow, 'tap', function(ev){
        		if($arrow.hasClass('arrow-active')){
        			$arrow.removeClass('arrow-active');
        			$box.removeClass('ul-active');
        			$atxt.html('更多');
        		}else{
        			$arrow.addClass('arrow-active');
        			$box.addClass('ul-active');
        			$atxt.html('收起');
        		}
        	});
        },
        getCard: function(){
        	var sortStr = window.localStorage.getItem('sort'),
        		dataPram = {};
        	if(sortStr){
        		dataPram = {'sort': sortStr};
        	}else if(sortStr == ''){
        		dataPram = {'sort': -1};
        	}
        	
        	var str = '';
        	$.ajax({
                url:"/card/index.html",
                dataType:"json",
                type:"post",
                data: dataPram,
                success:function(result) {
//                  	console.log(result)
                	
                	var objstr = result.sort;
                	window.localStorage.setItem("sort", objstr);
                	
                	if(result.cardList.length == 0){
                		return false;
                	}
                	
                	for(var i = 0; i < result.cardList.length; i++){
	            		//1:活动; 2:热点; 3:超值; 4:原创; 5:专题;
	            		str += '<div class="card">';
						str += '<div class="flex-horizontal card-head">';
						if(result.cardList[i].category == '1'){
							str += '<h1 class="fs-28 flex-average-item">活动</h1>';
						}else if(result.cardList[i].category == '2'){
							str += '<h1 class="fs-28 flex-average-item">热点</h1>';
						}else if(result.cardList[i].category == '3'){
							str += '<h1 class="fs-28 flex-average-item">超值</h1>';
						}else if(result.cardList[i].category == '4'){
							str += '<h1 class="fs-28 flex-average-item">原创</h1>';
						}else if(result.cardList[i].category == '5'){
							str += '<h1 class="fs-28 flex-average-item">专题</h1>';
						}
						if(result.cardList[i].category != '3'){
						str += '<h2 class="fs-28"><a href="/card/list.html?category='+ result.cardList[i].category +'">查看全部</a></h2>';
						}
						str += '<h3 data-id="'+ result.cardList[i].category +'">';
						str += '<ul>';
						str += '<li class="fs-28" data-action="top" onClick="javascript:_hmt.push([\'_trackEvent\', \''+ result.cardList[i].category +' -- 置顶\', \'置顶\']);">置顶</li>';
						str += '<li class="fs-28" data-action="close" onClick="javascript:_hmt.push([\'_trackEvent\', \''+ result.cardList[i].category +' -- 关闭\', \'关闭\']);">关闭</li>';
						str += '</ul>';
						str += '</h3>';
						str += '</div>';
						if(result.cardList[i].category == '1'){
							str += '<div class="card-activity card-wrapper">';
							str += '<ul>';
							for(var j = 0; j < result.cardList[i].details.length; j++){
								str += '<li>';
								str += '<a href="/card/details.html?cateid='+ result.cardList[i].category +'&id='+ result.cardList[i].details[j].id +'" class="flex-horizontal">';
								str += '<div class="imgbox"><img class="lazyload" data-original="'+ cdnStaticDomain + result.cardList[i].details[j].picture +'"></div>';
								str += '<div class="flex-average-item flex-vertical">';
								str += '<h1 class="fs-28 ellipsis2">'+ result.cardList[i].details[j].title +'</h1>';
								str += '<h2 class="fs-24">嘉宾：'+ result.cardList[i].details[j].guests +'</h2>';
								str += '<h2 class="fs-24">时间：'+ result.cardList[i].details[j].pubDateStr +' '+ result.cardList[i].details[j].weekday +' 丨 '+ result.cardList[i].details[j].cityStr +'</h2>';
								str += '</div>';
								str += '</a>';
								str += '</li>';
							}
							str += '</ul>';
							str += '</div>';
						}else if(result.cardList[i].category == '2'){
							str += '<div class="card-hotspot card-wrapper">';
							str += '<ul>';
							for(var k = 0; k < result.cardList[i].details.length; k++){
								str += '<li>';
								str += '<a href="/card/details.html?cateid='+ result.cardList[i].category +'&id='+ result.cardList[i].details[k].id +'" class="flex-horizontal">';
								str += '<h1 class="fs-28 flex-average-item ellipsis">'+ result.cardList[i].details[k].title +'</h1>';
								str += '<h2 class="fs-24">'+ result.cardList[i].details[k].showCreateDate +'</h2>';
								str += '</a>';
								str += '</li>';
							}
							str += '</ul>';
							str += '</div>';
						}else if(result.cardList[i].category == '3'){
							str += '<div class="card-supervalue card-wrapper">';
							str += '<div class="banner">';
							str += '<div class="swiper-container swiper-banner swiper-container-horizontal">';
							str += '<div class="swiper-wrapper">';
							for(var l = 0; l < result.cardList[i].details.banner.length; l++){
								str += '<div class="swiper-slide"><a href="/card/details.html?cateid='+ result.cardList[i].category +'&id='+ result.cardList[i].details.banner[l].id +'"><img class="lazyload" data-original="'+ cdnStaticDomain + result.cardList[i].details.banner[l].picture +'"></a></div>';
							}
							str += '</div>';
							str += '<div class="swiper-pagination"></div>';
							str += '</div>';
							str += '</div>';
							str += '<div class="imglist">';
							str += '<ul class="flex-horizontal">';
							for(var p = 0; p < result.cardList[i].details.smallpic.length; p++){
								str += '<li><a href="/card/details.html?cateid='+ result.cardList[i].category +'&id='+ result.cardList[i].details.smallpic[p].id +'"><img class="lazyload" data-original="'+ cdnStaticDomain + result.cardList[i].details.smallpic[p].picture +'"></a></li>';
							}
							str += '</ul>';
							str += '</div>';
							str += '</div>';
						}else if(result.cardList[i].category == '4'){
							for(var m = 0; m < result.cardList[i].details.length; m++){
								str += '<div class="card-original card-wrapper">';
								str += '<a href="/card/details.html?cateid='+ result.cardList[i].category +'&id='+ result.cardList[i].details[m].id +'">';
								str += '<div class="imgbox"><img class="lazyload" data-original="'+ cdnStaticDomain + result.cardList[i].details[m].picture +'"></div>';
								str += '<h1 class="fs-28">'+ result.cardList[i].details[m].title +'</h1>';
								str += '<p class="fs-24">'+ result.cardList[i].details[m].intro +'</p>';
								str += '</a>';
								str += '</div>';
							}
						}else if(result.cardList[i].category == '5'){
							str += '<div class="card-classify card-wrapper">';
							str += '<ul class="clearfix">';
							for(var n = 0; n < result.cardList[i].details.length; n++){
								str += '<li><a href="/card/details.html?cateid='+ result.cardList[i].category +'&id='+ result.cardList[i].details[n].id +'" class="fs-28 ellipsis">'+ result.cardList[i].details[n].title +'</a></li>';
							}
							str += '</ul>';
							str += '</div>';
						}
						if(result.cardList[i].category != '1' && result.cardList[i].category != '3'){
							if(result.cardList[i].category == '4'){
								str += '<div class="card-foot fs-24 t-r"><a href="javascript:void(0);" id="refresh-'+ result.cardList[i].category +'" data-refresh="'+ result.cardList[i].category +'" data-page="1" data-size="'+ result.cardList[i].details.length +'">换一个</a></div>';								
							}else{
								str += '<div class="card-foot fs-24 t-r"><a href="javascript:void(0);" id="refresh-'+ result.cardList[i].category +'" data-refresh="'+ result.cardList[i].category +'" data-page="1" data-size="'+ result.cardList[i].details.length +'">换一批</a></div>';									
							}
						}
						
						str += '</div>';
	            	}
                	
                	$('.index-card').html(str);
                	index.cardOperate();
        			index.superValueSwiper();
        			
        			var lazyImg = $('.index-card .lazyload');
	            	if(lazyImg){
	            		iknow.imgLazyLoad();
	            	}
                },
                error: function() {
                    iknow.alert("网络连接出错，请重试！");
                }
            });
        },
        cardOperate: function(){
        	var body = $('body'),
        		indexCard = $('.index-card');
        		
        	touch.on(body, 'tap', function(ev){
        		var obj = $(this),
        			_operateUL = indexCard.find('.card-head h3 ul'),
        			objUL = obj.find('ul');
        			
        		_operateUL.removeClass('active');
        		if(obj.attr('data-id')){
        			if(!objUL.hasClass('active')){
        				objUL.addClass('active');
        			}
        		}else if(obj.attr('data-action')){
        			indexCard.css('pointer-events', 'none');
        			var targetID = obj.parent().parent().attr('data-id');
        			if(obj.attr('data-action') == 'top'){
        				index.cardTop(targetID);
        			}else if(obj.attr('data-action') == 'close'){
        				index.cardDelete(targetID);
        			}
        		}else if(obj.attr('data-refresh')){
        			var refreshID = obj.attr('id');
        			index.cardRefresh(refreshID);
        		}
        		return false;
        	});
        },
        cardTop: function(targetID){
        	var sortStr = window.localStorage.getItem('sort'),
        		idArray = sortStr.split(',');
        		
        	if(targetID == idArray[0]){
    			return false;
    		}
    		var current = $('[data-id = "'+ targetID +'"]').parent().parent(),
    			currentH = current.height(),
    			indexCard = $('.index-card'),
    			order = index.getOrder(targetID),
    			marginBottom = $(window).width() * 0.04,
    			beforeTotal = 'translate3d(0, -'+ index.getTop(order) +'px, 0)';
    		
    		for(var i = 0; i < order; i++){
    			var beforeID = idArray[i];
    			$('[data-id = "'+ beforeID +'"]').parent().parent().css({
    				'-webkit-transition' : '-webkit-transform 0.5s ease-in-out',
    				'transition' : 'transform 0.5s ease-in-out',
    				'-webkit-transform' : 'translate3d(0, '+ (currentH + marginBottom) +'px, 0)',
    				'transform' : 'translate3d(0, '+ (currentH + marginBottom) +'px, 0)'
    			});
    		}
			current.css({
				'-webkit-transition' : '-webkit-transform 0.52s ease-in-out',
    			'transition' : 'transform 0.52s ease-in-out',
				'-webkit-transform' : beforeTotal,
				'transform' : beforeTotal
			});
			var t = setTimeout(function(){
				clearTimeout(t);
          		$('.card').removeAttr('style');
          		indexCard.prepend(current);
        		idArray.splice(parseInt(order), 1);
        		idArray.splice(0, 0, targetID);
        		var idArrayStr = idArray.join(',');
        		window.localStorage.setItem("sort", idArrayStr);
        		indexCard.removeAttr('style');
        	}, 500);
        },
        getTop: function(order){
        	var card = $('.card'),
        		cardLen = card.length,
        		sortStr = window.localStorage.getItem('sort'),
        		idArray = sortStr.split(','),
        		str = 0;
        	
        	for(var i = 0; i < order; i++){
        		str = parseInt(str) + parseInt($('[data-id = "'+ idArray[i] +'"]').parent().parent().height()) + $(window).width() * 0.04;
        	}
        	return str;
        },
        cardDelete: function(targetID){
    		var current = $('[data-id = "'+ targetID +'"]').parent().parent(),
    			order = index.getOrder(targetID),
    			sortStr = window.localStorage.getItem('sort'),
        		idArray = sortStr.split(',');
    		idArray.splice(parseInt(order), 1);
    		var idArrayStr = idArray.join(',');
        	window.localStorage.setItem("sort", idArrayStr);
    		current.remove();
    		clearTimeout(de);
    		var de = setTimeout(function(){
    			$('.index-card').removeAttr('style');
    		},200);
        },
        getOrder: function(targetID){
        	var sortStr = window.localStorage.getItem('sort'),
        		idArray = sortStr.split(',');
			for(var key in idArray){
    			if(idArray[key] == targetID){
    				return key;
    			}
    		}
		},
        cardSetTop: function(){
        	//未登录
        	if(!isLogin){
        		return false;
        	}
        	
        	var sortStr = window.localStorage.getItem('sort'),
        		sort = '';
        	if(sortStr){
        		sort = sortStr
        	}else{
        		//卡片全部关闭的时候
        		sort = -1;
        	}
        	
        	$.ajax({
                url:"/card/setTop.html?sort=" + sort,
                dataType:"json",
                type:"post",
                data: {
                    
                },
                success:function(result) {
//                    	console.log('setTop : ' + result);
                },
                error: function() {
                    
                }
            });
        },
        cardRefresh: function(refreshID){
        	var obj = $('#'+refreshID),
        		cardType = obj.attr('data-refresh'),
        		cardPage = parseInt(obj.attr('data-page')) + 1,
        		cardSize = obj.attr('data-size'),
        		$wrapper = obj.parent().parent().find('.card-wrapper'),
        		$box = '';
//          	console.log('cardType: '+cardType+'; cardPage: '+cardPage+'; cardSize: '+cardSize);
        	
        	$.ajax({
                url:"/card/anotherbatch/"+ cardType +".html",
                dataType:"json",
                type:"post",
                data: {
                    pageNo : cardPage,
                    size : cardSize
                },
                success:function(result) {
//                    	console.log(result);
                  	var str = '';
                  	//1:活动; 2:热点; 3:超值; 4:原创; 5:专题;
                  	if(cardType == 2){
                  		$box = $wrapper.find('ul');
                  		for(var k = 0; k < result.list.length; k++){
							str += '<li>';
							str += '<a href="/card/details.html?cateid='+ result.list[k].cardType +'&id='+ result.list[k].id +'" class="flex-horizontal">';
							str += '<h1 class="fs-28 flex-average-item ellipsis">'+ result.list[k].title +'</h1>';
							str += '<h2 class="fs-24">'+ result.list[k].showCreateDate +'</h2>';
							str += '</a>';
							str += '</li>';
						}
                  	}else if(cardType == 4){
                  		$box = $wrapper;
                  		for(var m = 0; m < result.list.length; m++){
							str += '<a href="/card/details.html?cateid='+ result.list[m].cardType +'&id='+ result.list[m].id +'">';
							str += '<div class="imgbox"><img class="lazyload" data-original="'+ cdnStaticDomain + result.list[m].picture +'"></div>';
							str += '<h1 class="fs-28">'+ result.list[m].title +'</h1>';
							str += '<p class="fs-24">'+ result.list[m].intro +'</p>';
							str += '</a>';
						}
                  	}else if(cardType == 5){
                  		$box = $wrapper.find('ul');
                  		for(var n = 0; n < result.list.length; n++){
							str += '<li><a href="/card/details.html?cateid='+ result.list[n].cardType +'&id='+ result.list[n].id +'" class="fs-28 ellipsis">'+ result.list[n].title +'</a></li>';
						}
                  	}
                  	
                  	$box.html(str);
                  	var lazyImg = $box.find('.lazyload');
	            	if(lazyImg){
	            		iknow.imgLazyLoad();
	            	}
                  	if(result.isLastPage){
                  		cardPage = 0;
                  	}
                  	obj.attr('data-page', cardPage);
                },
                error: function() {
                    iknow.alert('刷新失败！请重试！');
                }
            });
        },
        superValueSwiper: function(){
        	var banner = $('.index-card .swiper-banner');
        	if(banner){
        		//banner
               	var swiper_banner = new Swiper('.swiper-banner', {
		    		pagination: '.swiper-banner .swiper-pagination',
			        loop: true
			    });
        	}
        },
        wechatShare: function(){
        	var title = '【我懂】付费制一对一经验对话平台 m.iknow.tm',
        		desc = '有难题，上【我懂】m.iknow.tm',
        		link = 'http://m.iknow.tm',
        		imgUrl = staticDomain +'/'+ assetsVersion + '/images-mb/download-02.png';
        	iknow.wechatShareReady(title, desc, link, imgUrl);
        }
    }

    index.init();
});